<template>
  <div>
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名:">
          <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            :disabled="keyword ? false : true"
            @click="search"
            type="primary"
          >
            搜索
          </el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card @selection-change="selectchange" style="margin: 10px 0px">
      <el-button @click="addUser" type="primary">添加用户</el-button>
      <el-button
        :disabled="selectidArr.length ? false : true"
        @click="deleteselectUser"
        type="primary"
      >
        批量删除
      </el-button>
      <el-table :data="userArr">
        <el-table-column
          type="selection"
          align="center"
          border
        ></el-table-column>
        <el-table-column
          label="#"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="用户名"
          align="center"
          prop="username"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户名称"
          align="center"
          prop="name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户角色"
          align="center"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" style="width: 500px" align="center">
          <template #="{ row, $index }">
            <el-button
              icon="User"
              size="small"
              @click="setrole(row)"
              type="primary"
            >
              分配角色
            </el-button>
            <el-button
              icon="Edit"
              size="small"
              @click="updateUser(row)"
              type="primary"
            >
              编辑
            </el-button>

            <el-popconfirm
              :title="`你确定删除${row.username}吗?`"
              width="260px"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button icon="Delete" size="small" type="primary">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9, 11]"
        :background="true"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="getHasUser"
        @size-change="handler"
      />
    </el-card>
    <!-- 添加账号//更新账号 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="formref">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请输入用户姓名"
              v-model="userParams.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              placeholder="请输入用户昵称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input
              placeholder="请输入用户密码"
              v-model="userParams.password"
              v-if="!userParams.id"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 职位分配 -->
    <el-drawer v-model="drawer2">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.username" :disables="true"></el-input>
          </el-form-item>
          <el-form-item label="职位列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="userRole"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="(Role, index) in allRole"
                :key="index"
                :label="Role"
              >
                {{ Role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer2 = false">取消</el-button>
          <el-button type="primary" @click="confirmclick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import useLayOutSettingStore from '@/store/modules/setting'
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqSelectUser,
  reqRemoveUser,
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetUserRole,
} from '@/api/acl/user'
import {
  SetRoleData,
  UserResponseData,
  Records,
  User,
  AllRoleResponseData,
  AllRole,
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
let pageNo = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(0)
let userArr = ref<Records>([])
let drawer = ref<boolean>(false)
let drawer2 = ref<boolean>(false)
let userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
let formref = ref<any>()
onMounted(() => {
  getHasUser()
})
const getHasUser = async (pager = 1) => {
  pageNo.value = pager
  let result: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    userArr.value = result.data.records
  }
  console.log(result)
}
const handler = () => {
  getHasUser()
}
const addUser = () => {
  drawer.value = true
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  nextTick(() => {
    formref.value.clearValidate('username'),
      formref.value.clearValidate('name'),
      formref.value.clearValidate('password')
  })
}
const updateUser = (row: User) => {
  drawer.value = true
  Object.assign(userParams, row)
  nextTick(() => {
    formref.value.clearValidate('username'), formref.value.clearValidate('name')
  })
}
const save = async () => {
  formref.value.validate()
  let result: any = await reqAddOrUpdateUser(userParams)
  if (result.code == 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '添加成功',
    })
    getHasUser(userParams.id ? pageNo.value : 1)
    window.location.reload()
  } else {
    drawer.value = false
    ElMessage({
      type: 'error',
      message: userParams.id ? '更新失败' : '添加失败',
    })
  }
}

const cancel = () => {
  drawer.value = false
}
const validatorUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名应为至少五位'))
  }
}

const validatorname = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户昵称应为至少五位'))
  }
}

const validatorpassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('密码为至少六位'))
  }
}

const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  name: [{ required: true, trigger: 'blur', validator: validatorname }],
  password: [{ required: true, trigger: 'blur', validator: validatorpassword }],
}

const setrole = async (row: User) => {
  drawer2.value = true
  Object.assign(userParams, row)
  let result: AllRoleResponseData = await reqAllRole(userParams.id as number)
  if (result.code == 200) {
    allRole.value = result.data.allRolesList
    userRole.value = result.data.assignRoles
  }
}

const checkAll = ref<boolean>(false)
let userrole = ref(['销售'])
let allRole = ref<AllRole>([])
let userRole = ref<AllRole>([])
let selectidArr = ref<any>([])
let allrole = ref([
  '前台',
  '销售',
  '经理',
  '前端工程师',
  'Java后端工程师',
  '财务',
  '行政',
  '地区经理',
])
const isIndeterminate = ref<boolean>(true)
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allrole.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allrole.value.length
}
const confirmclick = async () => {
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item) => {
      return item.id as number
    }),
  }
  let result: any = await reqSetUserRole(data)
  if (result.code == 200) {
    ElMessage({ type: 'succes', message: '分配成功' })
    ;(drawer2.value = false), getHasUser(pageNo.value)
  }
}
const deleteUser = async (userid: number) => {
  let result: any = await reqRemoveUser(userid)
  if (result.code == 200) {
    ElMessage({ type: 'succes', message: '删除成功' })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
const selectchange = (value: any) => {
  selectidArr.value = value
}
const deleteselectUser = async () => {
  let idsList: any = selectidArr.value.map((item) => {
    return item.id
  })
  let result: any = await reqSelectUser(idsList)
  if (result.code == 200) {
    ElMessage({ type: 'succes', message: '删除成功' })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
// 搜索与重置
let keyword = ref<string>('')
const search = () => {
  getHasUser()
  keyword.value = ''
}
const reset = () => {
  SettingStore.refsh = !SettingStore.refsh
}
let SettingStore = useLayOutSettingStore()
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
